import {Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, MenuController, Content, AlertController} from 'ionic-angular';
import {DishProvider} from "../../../providers/DishProvider";
import {CustomerProvider} from "../../../providers/customerProvider";
import {CategoryProvider} from "../../../providers/category";
import {KitProvider} from "../../../core/foundations/KitProvider";
import {CartProvider} from "../../../providers/cartProvider";
import {Cart} from "../../../models/Cart";
import {HomePage} from "../home/home";
import {OrderProvider} from "../../../providers/orderProvider";
import {Observable} from "rxjs/Observable";
import {PlacedOrderPage} from "../placed-order/placed-order";


/**
 * Generated class for the ShoppingCartPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-shopping-cart',
  templateUrl: 'shopping-cart.html',
})
export class ShoppingCartPage {
  @ViewChild(Content) content: Content;
  carts: Cart[];
  hasDish = false;
  Tax: number;
  Tips: number;
  subTotal = 0.00;
  Total = 0.00;

  constructor(public navCtrl: NavController,
              public menu: MenuController,
              public alert: AlertController,
              public auth: CustomerProvider,
              public dishProd: DishProvider,
              public cartProd: CartProvider,
              public kit: KitProvider,
              public cateProd: CategoryProvider,
              public orderProd: OrderProvider) {
  }


  ionViewDidLoad() {
    let loading = this.kit.loadingPresent();
    this.cartProd.getCart().catch(err => {
      loading.dismiss();
      console.log('Error:', err);
      return Observable.throw(err);
    }).subscribe(res => {
      loading.dismiss();
      this.carts = res.data as Cart[];
      this.hasDish = this.carts.length > 0;
      this.subTotal = this.cartProd.total;
      console.log(this.subTotal);
      this.calcTotal();
      this.content.resize();
    });
    this.content.resize();

  }

  clear() {
    this.cartProd.clearCart().subscribe(res => {
      this.carts = null;
      this.hasDish = false;
      this.subTotal = 0;
    });
  }

  setHome() {
    this.navCtrl.setRoot(HomePage, {});
  }

  confirm() {
    this.navCtrl.push(PlacedOrderPage)
  }

  onNumChanged(event, dish) {
    this.kit.cart.changeCart(dish, event.num).subscribe(res => {
      this.carts = res.data as Cart[];
      this.hasDish = this.carts.length > 0;
      this.subTotal = this.cartProd.total;
    });
  }

  calcTotal() {
    if (this.Tax != null && this.Tax > 0)
      this.Total = Number(this.subTotal) + Number(this.Tax * this.subTotal / 100)+.00;
    this.Tax = Number(this.Tax * this.subTotal);
    console.log('this.Tax',this.Tax);
    if (this.Tips != null && this.Tips > 0)
      this.Total = Number(this.Total) + Number(this.Tips);
  }


}
